package com.lambkit.plugin.scheduled;

import cn.hutool.cron.Scheduler;
import cn.hutool.cron.task.Task;
import com.lambkit.core.LifecycleException;
import com.lambkit.core.plugin.Plugin;
import com.lambkit.scheduled.ScheduleTask;
import com.lambkit.scheduled.ScheduleTaskInfo;

import java.util.List;

/**
 * 定时任务
 * @author yangyong(孤竹行)
 */
public class ScheduledPlugin extends Plugin {

    private List<ScheduleTaskInfo> tasks;

    private boolean matchSecond = false;

    private boolean daemon = false;

    private final Scheduler scheduler = new Scheduler();

    public ScheduledPlugin(boolean matchSecond, boolean daemon) {
        this.matchSecond = matchSecond;
        this.daemon = daemon;
    }

    public ScheduledPlugin addTask(String cron, Runnable task, boolean enable) {
        tasks.add(new ScheduleTaskInfo(cron, task, daemon, enable));
        //CronUtil.schedule(cron, task);
        return this;
    }

    public ScheduledPlugin addTask(String cron, Runnable task) {
        return addTask(cron, task, true);
    }

    public ScheduledPlugin addTask(String cron, ScheduleTask task, boolean enable) {
        tasks.add(new ScheduleTaskInfo(cron, task, daemon, enable));
        //CronUtil.schedule(cron, task);
        return this;
    }

    public ScheduledPlugin addTask(String cron, ScheduleTask task) {
        return addTask(cron, task, true);
    }

    @Override
    public void start() throws LifecycleException {
        for(ScheduleTaskInfo taskInfo : tasks) {
            if(!taskInfo.isEnable()) {
                continue;
            }
            if (taskInfo.getTask() instanceof Runnable) {
                scheduler.schedule(taskInfo.getCron(),  (Runnable) taskInfo.getTask());
            } else if (taskInfo.getTask() instanceof ScheduleTask) {
                scheduler.schedule(taskInfo.getCron(), (ScheduleTask) taskInfo.getTask());
            } else if (taskInfo.getTask() instanceof Task) {
                scheduler.schedule(taskInfo.getCron(), (Task) taskInfo.getTask());
            }
        }
        if(matchSecond) {
            // 支持秒级别定时任务
            scheduler.setMatchSecond(true);
        }
        scheduler.start();
    }

    @Override
    public void stop() throws LifecycleException {
        super.stop();
        for(ScheduleTaskInfo taskInfo : tasks) {
            if(!taskInfo.isEnable()) {
                continue;
            }
            if (taskInfo.getTask() instanceof ScheduleTask) {
                ScheduleTask scheduleTask = (ScheduleTask) taskInfo.getTask();
                scheduleTask.stop();
            }
        }
        scheduler.stop(true);
    }
}
